import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/extentions/kq_extentions.dart';
import '../../resources/kq_theme_colors.dart';
import '../../resources/l10n/kq_intl.dart';
import 'package:kq_flutter_core_widget/utils/ex/kq_ex.dart';
import 'package:kq_flutter_core_widget/utils/text_filed_utils.dart';
import 'package:kq_flutter_core_widget/widgets/button/kq_ink_well.dart';

import '../../theme/kq_theme_manager.dart';
import '../divider/kq_divider.dart';
import '../textFiled/kq_textfiled.dart';
import 'entity/kq_form_entity.dart';

/// 通用表单组件 - 输入上下限组件
///
/// [ItemType.editUpperLower]
///
/// @author 高裕
///
/// 结合 KqFormEntity 使用
class KqEditUpperLowerItemView extends StatefulWidget {
  /// 通用属性
  final KqFormEntity entity;

  const KqEditUpperLowerItemView({Key? key, required this.entity})
      : super(key: key);

  @override
  KqEditUpperLowerItemViewState createState() =>
      KqEditUpperLowerItemViewState();
}

class KqEditUpperLowerItemViewState extends State<KqEditUpperLowerItemView> {
  @override
  void initState() {
    widget.entity.widgetState = this;
    widget.entity.valuesForSubmit = widget.entity.valuesForShow;
    widget.entity.valuesForShow ??= [null, null];
    widget.entity.valuesForSubmit ??= [null, null];
    if (widget.entity.controllers != null &&
        widget.entity.valuesForShow != null) {
      if (widget.entity.controllers![1] != null &&
          widget.entity.valuesForShow![1] != null) {
        TextFiledUtil.setValue(
            widget.entity.controllers![1]!, widget.entity.valuesForShow![1]!);
      }
      if (widget.entity.controllers![2] != null &&
          widget.entity.valuesForShow![2] != null) {
        TextFiledUtil.setValue(
            widget.entity.controllers![2]!, widget.entity.valuesForShow![2]!);
      }
    }

    super.initState();
  }

  /// 主动刷新方法
  update() {
    if (mounted) {
      setState(() {});
    }
  }

  /// 定位到该条数据，滚动到屏幕中央
  location(ScrollController? scrollController) {
    if (scrollController == null) {
      return;
    }
    //拿到控件的位置
    var position = context.position();
    var dy = position?.dy;
    if (scrollController.hasClients && dy != null) {
      var util = KqScreenUtil();
      var screenHeight = util.screenHeight;
      var targetY = scrollController.offset + dy - screenHeight / 2;
      var maxY = scrollController.position.maxScrollExtent;
      scrollController.jumpTo(max(0, min(targetY, maxY)));
    }
  }

  @override
  Widget build(BuildContext context) {
    // 如果外层实体是反复重新创建的，则需要在此重新赋值
    widget.entity.widgetState = this;
    widget.entity.valuesForSubmit = widget.entity.valuesForShow;
    widget.entity.valuesForShow ??= [null, null];
    widget.entity.valuesForSubmit ??= [null, null];
    // 背景颜色
    var bgColor = widget.entity.backgroundColor ?? KqThemeColors.bgWhite;
    return Visibility(
      visible: widget.entity.visible,
      child: Column(
        children: [
          KqInkWell(
            onTap: () {
              if (widget.entity.onTap != null) {
                widget.entity.onTap!(widget.entity);
              }
            },
            borderWidth: 0,
            child: Container(
              color: widget.entity.showFocusBorder ? null : bgColor,
              padding: EdgeInsets.only(
                  right: widget.entity.paddingHorizontal ??
                      KqThemeManager.instance
                          .getConfig()
                          .formConfig
                          .paddingHorizontal ??
                      16.r),
              decoration: widget.entity.showFocusBorder
                  ? BoxDecoration(
                      color: bgColor,
                      border: Border.all(width: 1, color: KqThemeColors.bgBlue))
                  : null,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Row(
                    crossAxisAlignment: widget.entity.multiline
                        ? CrossAxisAlignment.baseline
                        : CrossAxisAlignment.center,
                    textBaseline: widget.entity.multiline
                        ? TextBaseline.alphabetic
                        : null,
                    children: <Widget>[
                      Container(
                        padding: EdgeInsets.only(right: 10.r),
                        margin: EdgeInsets.only(
                            top: widget.entity.paddingVertical ??
                                KqThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .paddingVertical ??
                                15.r,
                            bottom: widget.entity.paddingVertical ??
                                KqThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .paddingVertical ??
                                15.r),
                        child: Row(
                          children: <Widget>[
                            ///是否必填
                            Container(
                              alignment: Alignment.centerRight,
                              padding: EdgeInsets.only(
                                right: 2.r,
                              ),
                              width: widget.entity.paddingHorizontal ??
                                  KqThemeManager.instance
                                      .getConfig()
                                      .formConfig
                                      .paddingHorizontal ??
                                  16.r,
                              child: Text(
                                "∗",
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                    fontSize: KqThemeManager.instance
                                            .getConfig()
                                            .formConfig
                                            .mustInputFontSize ??
                                        14.sp,
                                    color: widget.entity.mustInput
                                        ? KqThemeColors.textRed
                                        : KqThemeColors.bgTransparent),
                              ),
                            ),

                            /// 标题
                            LimitedBox(
                              maxWidth: KqThemeManager.instance
                                      .getConfig()
                                      .formConfig
                                      .titleMaxWidth ??
                                  200.r,
                              child: Text(
                                widget.entity.title,
                                maxLines: widget.entity.multiline ? null : 1,
                                overflow: widget.entity.multiline
                                    ? null
                                    : TextOverflow.ellipsis,
                                style: widget.entity.titleStyle ??
                                    TextStyle(
                                        fontSize: KqThemeManager.instance
                                                .getConfig()
                                                .formConfig
                                                .titleFontSize ??
                                            16.sp,
                                        color: widget.entity.titleColor ??
                                            KqThemeColors.text26),
                              ),
                            )
                          ],
                        ),
                      ),
                      Expanded(
                        /// 输入框
                        child: Row(
                          children: [
                            /// 左边自定义控件
                            /// 自定义布局，来自实体类
                            widget.entity.customLeftView != null
                                ? widget.entity.customLeftView!(widget.entity)
                                : Container(),

                            // 为了和UI规范的标题和内容之间距离40
                            SizedBox(
                              width: 30.r,
                              height: 1.r,
                            ),
                            Expanded(
                              child: Padding(
                                padding: EdgeInsets.symmetric(vertical: 10.r),
                                child: Row(
                                  children: [
                                    Expanded(
                                        child: KqTextFiled(
                                      multiline: widget.entity.multiline,
                                      maxLines: 1,
                                      inputType: widget.entity.inputType,
                                      editable: widget.entity.isEditable(),
                                      forceShowPlaceHolder:
                                          widget.entity.forceShowPlaceHolder,
                                      controller: widget.entity.controllers?[0],
                                      textColor: widget.entity.contentColor,
                                      fontSize: KqThemeManager.instance
                                          .getConfig()
                                          .formConfig
                                          .contentFontSize,
                                      enableClearButton:
                                          widget.entity.enableClearButton,
                                      textAlign: TextAlign.end,
                                      newValue:
                                          widget.entity.valuesForShow?[0] ?? '',
                                      placeHolder: widget.entity.hint,
                                      maxCharCount: widget.entity.maxCharCount,
                                      inputFormatters:
                                          widget.entity.inputFormatters,
                                      onFocusChanged: (hasFocus) {
                                        widget.entity.onFocusChangedWidthIndex
                                            ?.call(hasFocus, 0);
                                      },
                                      onMonitor: (str) {
                                        widget.entity.onMonitorWidthIndex
                                            ?.call(widget.entity, str, 0);
                                      },
                                      onChanged: (text) {
                                        widget.entity.valuesForShow?[0] = text;
                                        widget.entity.valuesForSubmit?[0] =
                                            text;
                                        widget.entity.onChangedWidthIndex
                                            ?.call(text, 0);
                                      },
                                    )),
                                    SizedBox(
                                      width: 8.r,
                                    ),
                                    Visibility(
                                      visible: widget.entity.isEditable() ||
                                          (widget.entity.valuesForShow !=
                                                  null &&
                                              widget.entity.valuesForShow!
                                                      .length ==
                                                  2 &&
                                              widget.entity.valuesForShow![0]
                                                  .isNotNullOrEmpty &&
                                              widget.entity.valuesForShow![1]
                                                  .isNotNullOrEmpty),
                                      child: Text(
                                        "~",
                                        style: TextStyle(
                                          fontSize: 14.r,
                                          color: KqThemeColors.text26,
                                        ),
                                      ),
                                    ),
                                    SizedBox(
                                      width: 8.r,
                                    ),
                                    SizedBox(
                                      width: paintWidthWithTextStyle(
                                          widget.entity.valuesForShow?[1]),
                                      child: KqTextFiled(
                                        multiline: widget.entity.multiline,
                                        maxLines: 1,
                                        inputType: widget.entity.inputType,
                                        editable: widget.entity.isEditable(),
                                        forceShowPlaceHolder:
                                            widget.entity.forceShowPlaceHolder,
                                        controller:
                                            widget.entity.controllers?[1],
                                        textColor: widget.entity.contentColor,
                                        fontSize: KqThemeManager.instance
                                            .getConfig()
                                            .formConfig
                                            .contentFontSize,
                                        enableClearButton:
                                            widget.entity.enableClearButton,
                                        textAlign: TextAlign.end,
                                        newValue:
                                            widget.entity.valuesForShow?[1] ??
                                                '',
                                        placeHolder: widget.entity.hint,
                                        maxCharCount:
                                            widget.entity.maxCharCount,
                                        inputFormatters:
                                            widget.entity.inputFormatters,
                                        onFocusChanged: (hasFocus) {
                                          widget.entity.onFocusChangedWidthIndex
                                              ?.call(hasFocus, 1);
                                        },
                                        onMonitor: (str) {
                                          widget.entity.onMonitorWidthIndex
                                              ?.call(widget.entity, str, 1);
                                        },
                                        onChanged: (text) {
                                          widget.entity.valuesForShow?[1] =
                                              text;
                                          widget.entity.valuesForSubmit?[1] =
                                              text;
                                          update();
                                          widget.entity.onChangedWidthIndex
                                              ?.call(text, 1);
                                        },
                                      ),
                                    )
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),

                      /// 单位
                      Visibility(
                        visible: widget.entity.unit.isNotNullOrEmpty,
                        child: Container(
                            padding: EdgeInsets.only(
                                left: widget.entity.isEditable() ? 10.r : 4.r,
                                top: widget.entity.paddingVertical ??
                                    KqThemeManager.instance
                                        .getConfig()
                                        .formConfig
                                        .paddingVertical ??
                                    15.r,
                                bottom: widget.entity.paddingVertical ??
                                    KqThemeManager.instance
                                        .getConfig()
                                        .formConfig
                                        .paddingVertical ??
                                    15.r),
                            child: Text(
                              widget.entity.unit ?? "",
                              style: TextStyle(
                                color: widget.entity.unitColor ??
                                    KqThemeColors.text26,
                                fontSize: KqThemeManager.instance
                                        .getConfig()
                                        .formConfig
                                        .unitFontSize ??
                                    16.sp,
                              ),
                            )),
                      ),

                      /// 自定义布局，来自实体类
                      widget.entity.customRightView != null
                          ? widget.entity.customRightView!(widget.entity)
                          : Container(),
                    ],
                  ),
                ],
              ),
            ),
          ),

          /// 自定义底部控件，来自实体类
          widget.entity.customBottomView != null
              ? widget.entity.customBottomView!(widget.entity)
              : Container(),

          /// 分割线
          Visibility(
              visible: !widget.entity.hideDivider, child: KqDivider(
            leftMargin: !widget.entity.dividerHorMarginEnable ? 0 : widget.entity.paddingHorizontal ??
                KqThemeManager.instance
                    .getConfig()
                    .formConfig
                    .paddingHorizontal ??
                16.r,
            rightMargin: !widget.entity.dividerHorMarginEnable ? 0 : widget.entity.paddingHorizontal ??
                KqThemeManager.instance
                    .getConfig()
                    .formConfig
                    .paddingHorizontal ??
                16.r,
          ))
        ],
      ),
    );
  }

  /// 计算文本宽度
  double paintWidthWithTextStyle(
    String? text,
  ) {
    final TextPainter textPainter = TextPainter(
        text: TextSpan(
            text:
                text.isNullOrEmpty ? KqIntl.currentResource.pleaseEnter : text,
            style: TextStyle(
                fontSize: KqThemeManager.instance
                    .getConfig()
                    .formConfig
                    .contentFontSize)),
        maxLines: 1,
        textDirection: TextDirection.ltr)
      ..layout(minWidth: 0, maxWidth: double.infinity);
    double size = textPainter.size.width +
        (text.isNullOrEmpty ? 0 : 4.r); // 加上4.r这个宽度，不会自动横滚
    return size > 120.r ? 120.r : size;
  }
}
